package com.github.ilioili.justdoit.components.activity;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.IntRange;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.github.ilioili.justdoit.R;
import com.github.ilioili.justdoit.common.AppBaseActivity;
import com.github.ilioili.justdoit.common.config.AnimationConfig;
import com.github.ilioili.justdoit.common.config.Colors;
import com.github.ilioili.justdoit.common.config.EventConstants;
import com.github.ilioili.justdoit.common.config.IntentKey;
import com.github.ilioili.justdoit.model.dao.ScheduleEventDao;
import com.github.ilioili.justdoit.model.pojo.Category;
import com.github.ilioili.justdoit.model.pojo.ScheduleEvent;
import com.github.ilioili.justdoit.components.receiver.AlarmReceiver;
import com.github.ilioili.justdoit.util.CompatUtil;
import com.github.ilioili.justdoit.util.DateRepeatUtil;
import com.github.ilioili.justdoit.util.DateUtil;
import com.github.ilioili.justdoit.util.ViewUtil;
import com.github.ilioili.justdoit.widget.CircleAnimationFrame;
import com.github.ilioili.justdoit.widget.CircularRecyclerWheelView;
import com.github.ilioili.justdoit.widget.WatchTimePicker;
import com.taihe.template.base.injection.Id;
import com.taihe.template.base.injection.Layout;
import com.taihe.template.base.util.NullUtil;
import com.taihe.template.base.util.ToastUtil;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

@Layout(R.layout.activity_create_or_modify)
public class CreateOrModifyActivity extends AppBaseActivity {
    public static final String INTENT_KEY_X_LOC = "x";
    public static final String INTENT_KEY_Y_LOC = "y";
    public static final String INTENT_KEY_COLOR = "color";
    public static final String INTENT_KEY_TYPE = "type";
    @Id(R.id.circle_animation_frame)
    private CircleAnimationFrame circleAnimationFrame;
    @Id(R.id.tab_everyweek)
    private View vTabEveryWeek;
    @Id(R.id.tab_everymonth)
    private View vTabEveryMonth;
    @Id(R.id.week_day_pick_view)
    private ViewGroup vWeekDayPickView;
    @Id(R.id.month_day_pick_view)
    private ViewGroup vMonthDayPickView;
    @Id(R.id.et_name)
    private AutoCompleteTextView etName;
    @Id(R.id.textInputLayout)
    private TextInputLayout textInputLayout;
    @Id(R.id.toolbar)
    private Toolbar toolBar;
    @Id(R.id.repeat_layout)
    private View vRepeatLayout;
    @Id(R.id.switch_alarm)
    private SwitchCompat alarmSwitch;
    @Id(R.id.switch_imergency)
    private SwitchCompat emergencySwitch;
    @Id(R.id.switch_importance)
    private SwitchCompat importanceSwitch;
    @Id(R.id.tv_alarm_time)
    private TextView tvAlarmTime;
    @Id(R.id.coordinatorLayout)
    private CoordinatorLayout vTopLayout;
    @Id(R.id.tv_repeat)
    private TextView tvRepeat;
    @Id(R.id.tv_date_start)
    private TextView tvDateStart;
    @Id(R.id.tv_date_end)
    private TextView tvDateEnd;
    @Id(R.id.tv_emergency)
    private TextView tvEmergency;
    @Id(R.id.tv_category)
    private TextView tvCagegory;
    @Id(R.id.tv_importance)
    private TextView tvImportance;
    @Id(R.id.horizontalWheelView)
    private CircularRecyclerWheelView recyclerWheelView;

    public static final String INTENT_KEY_HABBIT = "HABBIT";
    private ScheduleEvent scheduleEvent;

    public static Intent newIntent(Context context, @IntRange(from = 0, to = 2) int type, int xLocationInWindow, int yLocationInWindow, int color) {
        Intent it = new Intent(context, CreateOrModifyActivity.class);
        it.putExtra(INTENT_KEY_X_LOC, xLocationInWindow);
        it.putExtra(INTENT_KEY_Y_LOC, yLocationInWindow);
        it.putExtra(INTENT_KEY_COLOR, color);
        it.putExtra(INTENT_KEY_TYPE, type);
        return it;
    }

    public static Intent newIntent(Context context, @NotNull ScheduleEvent scheduleEvent, int xLocationInWindow, int yLocationInWindow, int color) {
        Intent it = new Intent(context, CreateOrModifyActivity.class);
        it.putExtra(INTENT_KEY_X_LOC, xLocationInWindow);
        it.putExtra(INTENT_KEY_Y_LOC, yLocationInWindow);
        it.putExtra(INTENT_KEY_COLOR, color);
        it.putExtra(INTENT_KEY_HABBIT, scheduleEvent);
        return it;
    }

    private int getSelectedChildNum(ViewGroup viewGroup) {
        int sum = 0;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            if (viewGroup.getChildAt(i).isSelected())
                sum++;
        }
        return sum;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.create, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_search) {
            startActivity(SearchActivity.newIntent(this));
            overridePendingTransition(0, 0);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initScheduleEvent();
        setSupportActionBar(toolBar);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(CreateOrModifyActivity.this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.HintList));
        etName.setAdapter(adapter);
        alarmSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                scheduleEvent.alarm = isChecked;
                AlarmReceiver.setAlarm(getApplicationContext(), scheduleEvent);
                updateAlarmTextView();
            }
        });
        importanceSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                tvImportance.setText(isChecked ? R.string.important : R.string.unimportant);
            }
        });
        emergencySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                tvEmergency.setText(isChecked ? R.string.emergent : R.string.unemergent);
            }
        });
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int[] loc = ViewUtil.getViewCenterLoc(v);
                getIntent().putExtra(INTENT_KEY_X_LOC, loc[0]);
                getIntent().putExtra(INTENT_KEY_Y_LOC, loc[1]);
                finish();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        for (int i = 0; i < 31; i++) {
            vMonthDayPickView.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setSelected(!v.isSelected());
                    int selectedChildNum = getSelectedChildNum(vMonthDayPickView);
                    if (0 == selectedChildNum) {
                        v.setSelected(true);
                        Snackbar.make(vMonthDayPickView, R.string.snack_at_least_choose_one_day, Snackbar.LENGTH_SHORT).show();
                    }
                    updateRepeatTextView();
                }
            });
        }
        for (int i = 0; i < 7; i++) {
            vWeekDayPickView.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setSelected(!v.isSelected());
                    if (0 == getSelectedChildNum(vWeekDayPickView)) {
                        v.setSelected(true);
                        Snackbar.make(vWeekDayPickView, R.string.snack_at_least_choose_one_day, Snackbar.LENGTH_SHORT).show();
                    }
                    updateRepeatTextView();
                }
            });
        }
        freshUi();
        circleAnimationFrame.expand(true, getIntent().getIntExtra(INTENT_KEY_X_LOC, 0), getIntent().getIntExtra(INTENT_KEY_Y_LOC, 0), AnimationConfig.MEDIUM, getIntent().getIntExtra(INTENT_KEY_COLOR, Color.TRANSPARENT));
    }

    private void initScheduleEvent() {
        scheduleEvent = (ScheduleEvent) getIntent().getSerializableExtra(INTENT_KEY_HABBIT);
        if (null == scheduleEvent) {
            scheduleEvent = new ScheduleEvent();
            scheduleEvent.id = scheduleEvent.createTime = System.currentTimeMillis();
            scheduleEvent.type = getIntent().getIntExtra(INTENT_KEY_TYPE, 0);
            scheduleEvent.color = Colors.ARRAY[new Random().nextInt(Colors.ARRAY.length)];
            if (scheduleEvent.type == EventConstants.TYPE_EVENT) {
                if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 20) {//太晚就默认时间是第二天
                    scheduleEvent.startTime = DateUtil.getTodayStartTime() + DateUtil.DAY_MILISECOND;
                } else {
                    scheduleEvent.startTime = DateUtil.getTodayStartTime();
                }
            } else {
                scheduleEvent.startTime = DateUtil.getTodayStartTime();
            }
            scheduleEvent.timeSpent = 30;
            scheduleEvent.alarm = false;
            scheduleEvent.alermHour = 8;
            scheduleEvent.alermMinute = 30;
            scheduleEvent.isRepeat = scheduleEvent.type != EventConstants.TYPE_EVENT;
            scheduleEvent.repeatFlag = DateRepeatUtil.getMonthAlldayFlag(true);
            scheduleEvent.repeatFlag = DateRepeatUtil.getWeeklyAlldayFlag(true);
        }
    }

    private void setUpHorizontalWheelView() {
        final String[] list = new String[]{"0m", "3m", "5m", "10m", "15m", "30m", "45m", "1h", "1.5h", "2h", "2.5h", "3h", "3.5h", "4h", "5h", "6h", "8h", "10h", "12h"};
        final int[] values = new int[]{0, 3, 5, 10, 15, 30, 45, 60, 90, 120, 150, 180, 210, 240, 300, 360, 480, 600, 720};
        final RecyclerView.Adapter adapter = new RecyclerView.Adapter() {
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                TextView itemView = (TextView) getLayoutInflater().inflate(R.layout.time_item, parent, false);
                return new RecyclerView.ViewHolder(itemView) {
                    @Override
                    public String toString() {
                        return super.toString();
                    }
                };
            }

            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                TextView button = (TextView) holder.itemView;
                button.setBackgroundResource(R.drawable.option_item_bg);
                button.setText(list[position]);
            }

            @Override
            public int getItemCount() {
                return list.length;
            }
        };
        final CircularRecyclerWheelView.OnScrollListener onItemSelectedListener1 = new CircularRecyclerWheelView.OnScrollListener() {
            @Override
            public void onScrollStop(int position, View view) {
                scheduleEvent.timeSpent = values[position];
            }

            ArgbEvaluator argbEvaluator = new ArgbEvaluator();
            int selectColor = CompatUtil.getColor(CreateOrModifyActivity.this, R.color.font_cyan);
            int defaultColor = CompatUtil.getColor(CreateOrModifyActivity.this, R.color.font_gray);

            @Override
            public void onScrolling(View view, float offset, float maxOffset) {
                TextView button = (TextView) view;
//                float scale = 1 - Math.abs(offset / maxOffset * 0.5f);
//                button.setTextSize(15 * scale);
                float colorScale = 1 - Math.abs(offset * 7 / maxOffset);
                if (Math.abs(offset) > maxOffset / 7) colorScale = 0;
                button.setTextColor((int) argbEvaluator.evaluate(colorScale, defaultColor, selectColor));
            }
        };
        recyclerWheelView.setAdapter(true, 7, adapter, onItemSelectedListener1);
        for (int i = 0; i < values.length; i++) {
            if (scheduleEvent.timeSpent <= values[i]) {
                recyclerWheelView.getLayoutManager().scrollToPosition(i + values.length * 10000 - 3);
                break;
            }
        }
    }


    private void freshUi() {
        setUpHorizontalWheelView();
        vTopLayout.setBackgroundColor(scheduleEvent.color);
        if (scheduleEvent.type != EventConstants.TYPE_EVENT) {
            vRepeatLayout.setVisibility(View.VISIBLE);
            updateRepeatTextView();
            if (DateRepeatUtil.isWeeklyRepeat(scheduleEvent.repeatFlag)) {
                vTabEveryWeek.setSelected(true);
                vTabEveryMonth.setSelected(false);
                vMonthDayPickView.setVisibility(View.GONE);
                vWeekDayPickView.setVisibility(View.VISIBLE);
                for (int i = 0; i < 7; i++) {
                    vWeekDayPickView.getChildAt(i).setSelected(DateRepeatUtil.isDayOfWeekMatch(i + 1, scheduleEvent.repeatFlag));
                }
            } else {
                vTabEveryMonth.setSelected(true);
                vTabEveryWeek.setSelected(false);
                vWeekDayPickView.setVisibility(View.GONE);
                vMonthDayPickView.setVisibility(View.VISIBLE);
                for (int i = 0; i < 31; i++) {
                    vMonthDayPickView.getChildAt(i).setSelected(DateRepeatUtil.isDayOfMonthMatch(i + 1, scheduleEvent.repeatFlag));
                }
            }
            setGone(R.id.emergency_divider, R.id.emergency_layout, R.id.importance_divider, R.id.importance_layout);
        } else {
            switch (scheduleEvent.importance) {
                case EventConstants.QUADRANT_IMPORTANT_AND_IMERGENCY:
                    importanceSwitch.setChecked(true);
                    emergencySwitch.setChecked(true);
                    break;
                case EventConstants.QUADRANT_IMPORTANT_NOT_IMERGENCY:
                    importanceSwitch.setChecked(true);
                    emergencySwitch.setChecked(false);
                    break;
                case EventConstants.QUADRANT_NOT_IMPORTANT_BUT_IMERGENCY:
                    importanceSwitch.setChecked(false);
                    emergencySwitch.setChecked(true);
                    break;
                case EventConstants.QUADRANT_NOT_IMPORTANT_NOT_IMERGENCY:
                    importanceSwitch.setChecked(false);
                    emergencySwitch.setChecked(false);
                    break;
            }
        }

        if (scheduleEvent.alarm) {
            alarmSwitch.setChecked(true);
        }

        etName.setText(scheduleEvent.name);
        updateRepeatTextView();
        updateAlarmTextView();
        updateStartDateTextView();
        updateEndDateTextView();
        switch (scheduleEvent.type) {
            case EventConstants.TYPE_EVENT:
                textInputLayout.setHint(getString(R.string.hint_enter_event_name));
//                etName.setHint("输入事件名称");
                break;
            case EventConstants.TYPE_HABIT:
                textInputLayout.setHint(getString(R.string.hint_enter_habit_name));
                setVisiable(R.id.item_repeat, R.id.divider_repeat);
                break;
            case EventConstants.TYPE_TARGET:
                textInputLayout.setHint(getString(R.string.hint_enter_target_name));
                setVisiable(R.id.item_end_time, R.id.divider_end_time, R.id.item_repeat, R.id.divider_repeat);
                break;
        }

        if (null == scheduleEvent.categoryId) {
            tvCagegory.setText(R.string.select_category);
        } else {
            tvCagegory.setText(getString(R.string.category) + " " + scheduleEvent.categoryId);
        }
    }

    private void updateRepeatTextView() {
        if (scheduleEvent.isRepeat) {
            if (vTabEveryWeek.isSelected()) {
                int selectedChildNum = getSelectedChildNum(vWeekDayPickView);
                if (selectedChildNum == 7) {
                    tvRepeat.setText(R.string.repeat_dayly);
                } else {
                    tvRepeat.setText(getString(R.string.repeat_everyweek) + selectedChildNum + getString(R.string.unit_day));
                }
            } else {
                tvRepeat.setText(getString(R.string.repeat_everymonth) + getSelectedChildNum(vMonthDayPickView) + getString(R.string.unit_day));
            }
        } else {
            tvRepeat.setText(R.string.repeat_task);
        }
    }


    //选择主题颜色
    public void onClickTheme(View v) {//TODO
        startActivity(CategoryListActivity.newIntent(this, new CategoryListActivity.OnCategorySelectListener() {
            @Override
            public void onCategorySelect(Category category) {
                scheduleEvent.categoryId = category.name;
                final int colorStart = scheduleEvent.color;
                final int endColor = category.color;
                scheduleEvent.color = endColor;
                ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1).setDuration(AnimationConfig.LONG);
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    ArgbEvaluator argbEvaluator = new ArgbEvaluator();

                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        float animatedValue = (float) animation.getAnimatedValue();
                        int color = (int) argbEvaluator.evaluate(animatedValue, colorStart, endColor);
                        vTopLayout.setBackgroundColor(color);
                    }
                });
                valueAnimator.start();
                if (null == scheduleEvent.categoryId) {
                    tvCagegory.setText(R.string.select_category);
                } else {
                    tvCagegory.setText(getString(R.string.category) + " " + scheduleEvent.categoryId);
                }
            }
        }));
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    public void onClickImportant(View v) {
        importanceSwitch.setChecked(!importanceSwitch.isChecked());
    }

    public void onClickImergency(View v) {
        emergencySwitch.setChecked(!emergencySwitch.isChecked());
    }

    //完成
    public void onClickDone(View v) {
        String name = etName.getText().toString().trim();
        if (NullUtil.ept(name)) {
            Snackbar.make(etName, R.string.snack_what_do_u_wanna_do, Snackbar.LENGTH_SHORT).show();
            etName.postDelayed(new Runnable() {
                @Override
                public void run() {
                    etName.startAnimation(AnimationUtils.loadAnimation(CreateOrModifyActivity.this, R.anim.shake));
                    etName.requestFocus();
                }
            }, Snackbar.LENGTH_SHORT);
            return;
        }
        if (scheduleEvent.isRepeat) {
            if (vTabEveryWeek.isSelected()) {
                for (int childIndex = 0; childIndex < 7; childIndex++) {
                    scheduleEvent.repeatFlag = DateRepeatUtil.getWeeklyRepeatFlag(scheduleEvent.repeatFlag, childIndex + 1, vWeekDayPickView.getChildAt(childIndex).isSelected());
                }
                if (getSelectedChildNum(vWeekDayPickView) == 0) {
                    ToastUtil.showLongToast(getString(R.string.toast_set_repeat_mode));
                    return;
                }
            } else {
                for (int childIndex = 0; childIndex < 31; childIndex++) {
                    scheduleEvent.repeatFlag = DateRepeatUtil.getMonthlyRepeatFlag(scheduleEvent.repeatFlag, childIndex + 1, vMonthDayPickView.getChildAt(childIndex).isSelected());
                }
                if (getSelectedChildNum(vWeekDayPickView) == 0) {
                    ToastUtil.showLongToast(getString(R.string.toast_set_repeat_mode));
                    return;
                }
            }
        }
        if (scheduleEvent.type == EventConstants.TYPE_TARGET) {
            if (scheduleEvent.endTime < scheduleEvent.startTime) {
                ToastUtil.showLongToast(getString(R.string.toast_time_error));
                return;
            }
        }
        if (emergencySwitch.isChecked()) {
            if (importanceSwitch.isChecked()) {
                scheduleEvent.importance = EventConstants.QUADRANT_IMPORTANT_AND_IMERGENCY;
            } else {
                scheduleEvent.importance = EventConstants.QUADRANT_NOT_IMPORTANT_BUT_IMERGENCY;
            }
        } else {
            if (importanceSwitch.isChecked()) {
                scheduleEvent.importance = EventConstants.QUADRANT_IMPORTANT_NOT_IMERGENCY;
            } else {
                scheduleEvent.importance = EventConstants.QUADRANT_NOT_IMPORTANT_NOT_IMERGENCY;
            }
        }
        scheduleEvent.name = name;
        ScheduleEventDao.replace(scheduleEvent);
        Intent data = new Intent();
        data.putExtra(IntentKey.GET_HABBIT, scheduleEvent);
        setResult(RESULT_OK, data);
        finish();
    }


    //选择每周重复
    public void onClickEveryWeek(View v) {
        if (v.isSelected()) {
            vWeekDayPickView.setSelected(!vWeekDayPickView.isSelected());
        } else {
            vTabEveryMonth.setSelected(false);
            vTabEveryWeek.setSelected(true);
            vMonthDayPickView.setVisibility(View.GONE);
            vWeekDayPickView.setVisibility(View.VISIBLE);
        }
        updateRepeatTextView();
    }

    //选择每月重复
    public void onClickEveryMonth(View v) {
        if (v.isSelected()) {
            vMonthDayPickView.setSelected(!vMonthDayPickView.isSelected());
        } else {
            vTabEveryMonth.setSelected(true);
            vTabEveryWeek.setSelected(false);
            vWeekDayPickView.setVisibility(View.GONE);
            vMonthDayPickView.setVisibility(View.VISIBLE);
        }
        updateRepeatTextView();
    }


    //设置提醒时间
    public void onClickSetAlarm(View v) {
        startActivity(PickTimeActivity.newIntent(this, new WatchTimePicker.OnTimeSelectListener() {
            @Override
            public void onTimeSelected(int hour, int minute) {
                scheduleEvent.alarm = true;
                AlarmReceiver.setAlarm(getApplicationContext(), scheduleEvent);
                scheduleEvent.alermHour = hour;
                scheduleEvent.alermMinute = minute;
                if (!alarmSwitch.isChecked()) {
                    alarmSwitch.setChecked(true);
                } else {
                    updateAlarmTextView();
                }
            }
        }));
        overridePendingTransition(0, 0);
    }

    //选择开始日期
    public void onClickPickStartDate(View v) {
        startActivity(PickDateActivity.newIntent(this, new PickDateActivity.OnDateSelectListener() {
            @Override
            public void onDateSelect(int year, int month, int day) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                calendar.set(Calendar.DAY_OF_MONTH, day);
                scheduleEvent.startTime = DateUtil.getDayStartTime(year, month, day);
                updateStartDateTextView();
            }
        }));
        overridePendingTransition(0, 0);
    }

    //选择结束日期
    public void onClickPickEndDate(View v) {
        startActivity(PickDateActivity.newIntent(this, new PickDateActivity.OnDateSelectListener() {
            @Override
            public void onDateSelect(int year, int month, int day) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR, year);
                calendar.set(Calendar.MONTH, month);
                calendar.set(Calendar.DAY_OF_MONTH, day);
                scheduleEvent.endTime = DateUtil.getDayStartTime(year, month, day);
                updateEndDateTextView();
            }
        }));
        overridePendingTransition(0, 0);
    }

    private void updateStartDateTextView() {
        if (DateUtil.isToday(scheduleEvent.startTime)) {
            tvDateStart.setText(R.string.start_day_today);
        } else if (DateUtil.isTomorrow(scheduleEvent.startTime)) {
            tvDateStart.setText(R.string.start_day_tomorrow);
        } else if (DateUtil.isTheDayAfterTomorrow(scheduleEvent.startTime)) {
            tvDateStart.setText(R.string.start_day_after_tomorrow);
        } else {
            tvDateStart.setText(getString(R.string.start_from) + new SimpleDateFormat(getString(R.string.format_time)).format(new Date(scheduleEvent.startTime)));
        }
    }

    private void updateEndDateTextView() {
        if (scheduleEvent.endTime == 0) {
            tvDateEnd.setText(R.string.end_date);
        } else if (DateUtil.isToday(scheduleEvent.endTime)) {
            tvDateEnd.setText(R.string.end_day_today);
        } else if (DateUtil.isTomorrow(scheduleEvent.endTime)) {
            tvDateEnd.setText(R.string.end_day_tomorrow);
        } else if (DateUtil.isTheDayAfterTomorrow(scheduleEvent.endTime)) {
            tvDateEnd.setText(R.string.end_day_after_tomorrow);
        } else {
            tvDateEnd.setText(getString(R.string.end_by) + new SimpleDateFormat(getString(R.string.format_time)).format(new Date(scheduleEvent.endTime)));
        }
    }


    private boolean isFinishing;

    @Override
    public void finish() {
        if (isFinishing) {
            return;
        } else {
            isFinishing = true;
        }
        circleAnimationFrame.collapse(true, getIntent().getIntExtra(INTENT_KEY_X_LOC, 0), getIntent().getIntExtra(INTENT_KEY_Y_LOC, 0), AnimationConfig.MEDIUM, false, new CircleAnimationFrame.CompleteListener() {
            @Override
            public void onComplete() {
                CreateOrModifyActivity.super.finish();
                overridePendingTransition(0, 0);
            }
        });
    }

    private void updateAlarmTextView() {
        if (scheduleEvent.alarm) {
            String hourStr = scheduleEvent.alermHour < 10 ? "0" + scheduleEvent.alermHour : "" + scheduleEvent.alermHour;
            String minuteStr = scheduleEvent.alermMinute < 10 ? "0" + scheduleEvent.alermMinute : "" + scheduleEvent.alermMinute;
            tvAlarmTime.setText(getString(R.string.alarm_time) + " " + hourStr + ":" + minuteStr);
        } else {
            tvAlarmTime.setText(R.string.alarm_settings);
        }
    }
}
